package org.hard.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: 王林博
 * @date: 2022年10月15日 16:21
 */
public class IPUtils {

    private final static String ipUrl = "http://pv.sohu.com/cityjson?ie=utf-8";

    public static String getIP() {

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        String toIp = "";
        try {
            URL url = new URL(ipUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine.append(read);
            }
            String objJson = inputLine.substring(inputLine.indexOf("=") + 1, inputLine.length() - 1);
            final JSON parse = JSONUtil.parse(objJson);
            final Object cip = parse.getByPath("cip");
            toIp = (String) cip;
        } catch (Exception e) {
            toIp = "";
        }
        return toIp;
    }
}
